package dyyx.echo;

import java.time.LocalDateTime;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import dyyx.util.CommUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandlerUseThreadPool extends ChannelInboundHandlerAdapter {

	private static final ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 20, 60L, TimeUnit.SECONDS,
			new SynchronousQueue<Runnable>());

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channelActive,remoteAddress=" + ctx.channel().remoteAddress() + ",eventLoop="
				+ ctx.channel().eventLoop());
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		// ctx.flush();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		System.out.println("channelRead.msg1="+msg+","+LocalDateTime.now());
		pool.submit(new Task(ctx, msg));
		System.out.println("channelRead.msg2="+msg+","+LocalDateTime.now());
	}

	private static class Task implements Runnable {
		private final Object msg;
		final ChannelHandlerContext ctx;

		public Task(ChannelHandlerContext ctx, Object msg) {
			this.ctx = ctx;
			this.msg = msg;
		}

		public void run() {
			System.out.println("task.msg=" + msg+","+LocalDateTime.now()+","+Thread.currentThread());
			// System.out.println("task.msg.info=" + msg.getClass());

	        String msgstr = msg.toString();
	        
	        if("fast".equals(msgstr)){
	        	// no sleep
	        }else{
	        	
	        	long sleep = CommUtil.getSleepTime(msgstr);
	        	
	        	// 模拟耗时
	        	if(sleep>0){
	                CommUtil.doSleep(sleep);
	        	}
	        }
	        
			System.out.println("task.writeAndFlush.msg=" + msg+","+LocalDateTime.now());


			if ("bye".equals(msg.toString())) {
				// write vs writeAndFlush
				ctx.writeAndFlush(msg + "\n");
			}if ("error".equals(msg.toString())) {
				// throw new RuntimeException("EchoServerHandler error");
				// ctx.writeAndFlush(msg+"\n");
				ctx.writeAndFlush(msg + "\n");
			} if("traffic".equals(msg.toString())){
				
				ctx.writeAndFlush(TraficCountHandler.getInfo().toString() + "\n");
				
			}else {
				ctx.writeAndFlush(msg + "\n");
			}

		}
	}

}
